package com.example.software.controller;

import com.example.software.dto.CompanyRegisterDTO;
import com.example.software.dto.LoginDTO;
import com.example.software.dto.WorkerRegisterDTO;
import com.example.software.service.UserService;
import com.example.software.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin // 添加跨域支持
public class AuthController {
    
    private static final Logger log = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private UserService userService;

    /**
     * 企业用户注册
     * @param registerDTO 注册信息
     * @return 注册结果
     */
    @PostMapping("/register/company")
    public Result<Boolean> registerCompany(@Valid @RequestBody CompanyRegisterDTO registerDTO) {
        boolean result = userService.registerCompany(registerDTO);
        return Result.success(result);
    }

    /**
     * 零工用户注册
     * @param registerDTO 注册信息
     * @return 注册结果
     */
    @PostMapping("/register/worker")
    public Result<Boolean> registerWorker(@Valid @RequestBody WorkerRegisterDTO registerDTO) {
        log.info("收到零工注册请求");
        try {
            // 打印关键注册信息（但不打印密码）
            log.info("零工注册信息：用户名={}, 姓名={}, 手机={}, 擅长工种={}", 
                registerDTO.getUsername(), registerDTO.getName(), 
                registerDTO.getPhone(), registerDTO.getSkillType());
            
            // 验证密码强度
            if (registerDTO.getPassword() == null || registerDTO.getPassword().length() < 8) {
                log.warn("密码强度不足: 长度小于8位");
                return Result.error("密码长度必须不小于8位");
            }
            
            boolean result = userService.registerWorker(registerDTO);
            log.info("零工注册结果: {}", result);
            return Result.success(result);
        } catch (Exception e) {
            log.error("零工注册处理异常", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户登录
     * @param loginDTO 登录信息
     * @return token
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Valid @RequestBody LoginDTO loginDTO) {
        String token = userService.login(loginDTO);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return Result.success(map);
    }

    @PostMapping("/validate/company-register")
    public Result<Void> validateCompanyRegister(@RequestBody Map<String, Object> data) {
        log.info("验证企业注册步骤数据：{}", data);
        try {
            Integer step = (Integer) data.get("step");
            if (step == null) {
                return Result.error("步骤参数不能为空");
            }
            
            if (step == 0) {
                validateStep1Data(data);
            } else if (step == 1) {
                validateStep2Data(data);
            } else {
                return Result.error("无效的步骤参数");
            }
            return Result.success();
        } catch (IllegalArgumentException e) {
            log.warn("数据验证失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("验证过程发生错误", e);
            return Result.error("验证失败，请稍后重试");
        }
    }

    private void validateStep1Data(Map<String, Object> data) {
        String companyName = (String) data.get("companyName");
        String companyAddress = (String) data.get("companyAddress");
        String companyType = (String) data.get("companyType");

        log.debug("验证第一步数据：companyName={}, companyAddress={}, companyType={}", 
                 companyName, companyAddress, companyType);

        if (!StringUtils.hasLength(companyName)) {
            throw new IllegalArgumentException("公司名称不能为空");
        }
        if (companyName.length() < 2 || companyName.length() > 50) {
            throw new IllegalArgumentException("公司名称长度必须在2-50个字符之间");
        }
        if (!StringUtils.hasLength(companyAddress)) {
            throw new IllegalArgumentException("公司地址不能为空");
        }
        if (!StringUtils.hasLength(companyType)) {
            throw new IllegalArgumentException("请选择公司类型");
        }
    }

    private void validateStep2Data(Map<String, Object> data) {
        String legalName = (String) data.get("legalName");
        String legalPhone = (String) data.get("legalPhone");
        String legalIdCard = (String) data.get("legalIdCard");

        log.debug("验证第二步数据：legalName={}, legalPhone={}, legalIdCard={}", 
                 legalName, legalPhone, legalIdCard);

        if (StringUtils.isEmpty(legalName)) {
            throw new IllegalArgumentException("法人姓名不能为空");
        }
        if (legalName.length() < 2 || legalName.length() > 20) {
            throw new IllegalArgumentException("法人姓名长度必须在2-20个字符之间");
        }
        if (StringUtils.isEmpty(legalPhone)) {
            throw new IllegalArgumentException("法人手机号不能为空");
        }
        if (!legalPhone.matches("^1[3-9]\\d{9}$")) {
            throw new IllegalArgumentException("请输入正确的手机号码");
        }
        if (StringUtils.isEmpty(legalIdCard)) {
            throw new IllegalArgumentException("法人身份证号不能为空");
        }
        if (!legalIdCard.matches("(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)")) {
            throw new IllegalArgumentException("请输入正确的身份证号码");
        }
    }

    /**
     * 创建管理员账号（仅用于系统初始化，生产环境应当禁用或添加额外安全措施）
     */
    @PostMapping("/create-admin")
    public Result<Boolean> createAdmin(@RequestParam String secretKey, @Valid @RequestBody LoginDTO adminDTO) {
        log.info("接收到创建管理员请求");
        
        // 验证秘钥（简单实现，实际应当使用更安全的方式）
        if (!"admin_secret_key".equals(secretKey)) {
            return Result.error("秘钥无效，无权创建管理员");
        }
        
        boolean result = userService.createAdmin(adminDTO);
        return Result.success(result);
    }
} 